from django.shortcuts import render, redirect

# Create your views here.
"""登录"""
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.contrib import messages


def login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
            next_url = request.GET.get('next')
            if next_url and request.is_safe_url(next_url, allowed_hosts={request.get_host()}):
                return HttpResponseRedirect(next_url)
            else:
                return HttpResponseRedirect(reverse_lazy('home'))
        else:
            messages.error(request, "用户名或密码错误")  # 添加错误信息
    return render(request, 'login.html')


def logout_view(request):
    logout(request)
    return redirect('login')


def home(request):
    if request.user.is_authenticated:
        return render(request, 'home.html', {'user': request.user})
    else:
        return redirect('login')


@login_required
def index(request):
    # 只有登录用户才能访问的页面
    context = {
        'active_page': "index"
    }
    print(context)  # 打印调试信息
    return render(request, 'home.html', context)
